<?php
class loginController
{
	private function check( $data, $password )
	{
		
		if( Kernel::layer('session')->getAccount() )
		{
			return false;
		}
		
		$Account = new OTS_Account;
		$Account->load( $data );
		if( !$Account->isLoaded() )
		{
			$Account->find( $data );
			
			if( !$Account->isLoaded() )
			{
				$Player = new OTS_Player;
				$Player->find( $data );
				
				if( !$Player->isLoaded() )
				{
					return false;
				}
				
				unset( $Account );
				$Account = $Player->account;
			}
		}
		
		if( $Account->isLoaded() and $Account->password == Kernel::layer('OTS')->password( $password ) )
		{
			return $Account;
		}
		else
		{
			return false;
		}
	}
	
	public function index()
	{
		if( Kernel::layer('session')->getAccount() )
		{
			Kernel::layer('controller')->load('account');
			return false;
		}
		
		Kernel::layer('view')->sub('login');
	}
	
	public function login()
	{
		if( !$_POST['data'] )
		{
			$this->index();
			return false;
		}
		
		$Account = $this->check($_POST['data'], $_POST['password']);
		if( !$Account )
		{
			Kernel::layer('view')->render( Kernel::layer('lang')->baddata );
			$this->index();
			return false;
		}
		
		Kernel::layer('session')->setAccount( $Account->id );
		Kernel::layer('session')->setPassword( $Account->password );
		Kernel::layer('session')->setExpire( ( $_POST['rememberMe'] == 'true' ) ? 0 : 1 );
		
		Kernel::layer('view')->render( Kernel::layer('lang')->logged );
	}

	public function logout()
	{
		Kernel::layer('session')->destroy();
		Kernel::layer('view')->render( Kernel::layer('lang')->logouted );
	}
}
?>